var source = function get(url) {
	new EventSource(url);
}

import {NativeEventSource,EventSourcePolyfill} from 'event-source-polyfill';
import {Base64} from 'js-base64';

function createSse(url, data,callback) {
	data = strToHexCharCode(data);
	let reqParam = {
		method: 'POST',
		headers: {'Authorization': 'Bearer ' + uni.getStorageSync('appToken'),'Content-Type': 'application/json'},
		body: data,
		timeout: 1000000
	};
	fetch(url, reqParam).then((response) => {
		var reader = response.body.getReader();
		var decoder = new TextDecoder('utf-8');
		return reader.read().then(function processResult(result) {
			if (result.done) {
				// uni.$u.http.get("/chat/trans/close");
				return;
			}
			var text = decoder.decode(result.value, {stream: true});
			console.log("text: " + JSON.stringify(text));
			try{
				if(text.indexOf("retry:3000") != -1){
					text = text.replace("retry:3000","");
				}
				if(text.indexOf("data:") != -1){
					text = text.replace("data:", "");
				}
				try{
					let jsonRet = JSON.parse(text);
					if(jsonRet && jsonRet.code == 403){
						let loginStr = "";
						// #ifdef H5
						loginStr = "<a href='/pages/login/index?type=useraccount'>去登录>></a>";
						// #endif
						callback && callback({recordId:0,content:'对不起，您还没有登录系统，暂不能使用本系统服务！' + loginStr});
						let tt = setTimeout(()=>{
							callback && callback({recordId:0, content:'[DONE]'});
							clearTimeout(tt);
						}, 600);
						return;
					}
				}catch(e1){
					console.log("e1: " + text + "->" + JSON.stringify(e1));
				}
			}catch(e){
				console.log("e: " + text + "->" + JSON.stringify(e));
			}
			console.log("text2: " + JSON.stringify(text));
			var lines = text.split('\n\n');
			console.log("lines: " + JSON.stringify(lines));
			lines.forEach(function(line) {
				if(line){
					line = line.trim();
					if(line == '：'){
						return;
					}
				}
				if (line && line.length > 0) {
					try {
						if(line.indexOf("data:") != -1){
							line = line.replace("data:", " ");
						}
						//console.log("line: " + JSON.stringify(line));
						if(typeof line === 'string'){
							line = JSON.parse(line);
							if(line.code == 999){
								//心跳消息不处理
								return;
							}
							if(line.code == 403){
								callback && callback({recordId:0,content:line.msg});
								let tt = setTimeout(()=>{
									callback && callback({recordId:0,content:'[DONE]'});
									clearTimeout(tt);
								}, 600);
								return;
							}
						}
						//console.log("json: " + JSON.stringify(line));
						if (line.content == '[DONE]') {
							callback && callback(line);
							return;
						}
						callback && callback(line);
					} catch (e) {
						console.log(e + " -> "+ line)
					}
				}
				// 处理接收到的数据
			});
			return reader.read().then(processResult);
		});
	}).catch(function(error) {
		// 处理连接错误
		console.log("处理连接错误", error);
	});
}

/**
 * HEX 字符串转String
 * @param {Object} hexCharCodeStr HEX字符串
 */
function hexCharCodeToStr(hexCharCodeStr) {
	if (!hexCharCodeStr) {
		return "";
	}
	var trimedStr = hexCharCodeStr.trim();
	var len = trimedStr.length;
	if (len % 2 !== 0) {
		return "";
	}
	var curCharCode;
	var resultStr = [];
	for (var i = 0; i < len; i = i + 2) {
		curCharCode = parseInt(trimedStr.substr(i, 2), 16);
		resultStr.push(String.fromCharCode(curCharCode));
	}
	return resultStr.join("");
}

/**
 * String字符串转HEX
 * @param {Object} str 字符串
 */
function strToHexCharCode(str) {
	if (str === "") {
		return "";
	} else {
		var hexCharCode = [];
		for (var i = 0; i < str.length; i++) {
			hexCharCode.push((str.charCodeAt(i)).toString(16));
		}
		return hexCharCode.join("");
	}
}


function urlDecode(str) {
	var ret = "";
	for (var i = 0; i < str.length; i++) {
		var chr = str.charAt(i);
		if (chr == "+") {
			ret += " ";
		} else if (chr == "%") {
			var asc = str.substring(i + 1, i + 3);
			if (parseInt("0x" + asc) > 0x7f) {
				ret += asc2str(parseInt("0x" + asc + str.substring(i + 4, i + 6)));
				i += 5;
			} else {
				ret += asc2str(parseInt("0x" + asc));
				i += 2;
			}
		} else {
			ret += chr;
		}
	}

	return ret;
}


module.exports = {
	createSse,
	hexCharCodeToStr,
	strToHexCharCode,
}